package com.tencent.qcloud.qiaoqiao.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.qcloud.qiaoqiao.R;
import com.tencent.qcloud.qiaoqiao.common.utils.TCConstants;
import com.tencent.qcloud.qiaoqiao.login.TCUserMgr;
import com.tencent.qcloud.qiaoqiao.mainui.list.TCVideoInfo;
import com.tencent.qcloud.qiaoqiao.play.TCVodPlayerActivity;
import com.tencent.qcloud.qiaoqiao.ui.BaseFragment;
import com.tencent.qcloud.qiaoqiao.ui.activity.CollectActivity;
import com.tencent.qcloud.qiaoqiao.ui.activity.WebViewActivity;
import com.tencent.qcloud.qiaoqiao.ui.adapter.CollectAdapter;
import com.tencent.qcloud.qiaoqiao.ui.bean.CollectBean;
import com.tencent.qcloud.qiaoqiao.ui.bean.UserInfoBean;
import com.tencent.qcloud.qiaoqiao.ui.net.FastJsonTools;
import com.tencent.qcloud.qiaoqiao.ui.net.HttpRequest;
import com.tencent.qcloud.qiaoqiao.ui.net.HttpResultListener;
import com.tencent.qcloud.qiaoqiao.ui.tools.Constant;
import com.tencent.qcloud.qiaoqiao.ui.tools.MyAppUtils;
import com.tencent.qcloud.qiaoqiao.ui.tools.utilCode.ToastUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.FormBody;
import okhttp3.RequestBody;


public class MineFragment extends BaseFragment {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.like_recyclerView)
    RecyclerView likeRecyclerView;
    @BindView(R.id.like_refreshLayout)
    SmartRefreshLayout likeRefreshLayout;
    @BindView(R.id.mine_my_video)
    TextView mineMyVideo;
    @BindView(R.id.mine_like_video)
    TextView mineLikeVideo;
    @BindView(R.id.myVideo_line)
    ImageView myVideoLine;
    @BindView(R.id.myLike_line)
    ImageView myLikeLine;
    @BindView(R.id.user_name_tv)
    TextView userNameTv;
    @BindView(R.id.guanzhu_btn)
    ImageView guanzhuBtn;
    @BindView(R.id.home_buy_btn)
    TextView homeBuyBtn;
    @BindView(R.id.dianzhan_video_btn)
    TextView dianzhanVideoBtn;
    @BindView(R.id.user_imageView)
    ImageView userImageView;

    private String userId;

    public static MineFragment newInstance(String userId) {
        MineFragment fragment = new MineFragment();
        Bundle args = new Bundle();
        args.putString("userId", userId);
        fragment.setArguments(args);
        return fragment;
    }

    private List<TCVideoInfo> palyVideoList;
    private List<CollectBean.ListBean> videoBeanList, likeBeanList;
    private CollectAdapter myVideoAdapter;
    private CollectAdapter likeAdapter;
    UserInfoBean collectBean;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_mine, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        videoBeanList = new ArrayList<>();
        likeBeanList = new ArrayList<>();

        myVideoAdapter = new CollectAdapter();
        recyclerView.setAdapter(myVideoAdapter);
        myVideoAdapter.addData(videoBeanList);

        likeAdapter = new CollectAdapter();
        likeRecyclerView.setAdapter(likeAdapter);
        likeAdapter.addData(likeBeanList);
//        //触发自动刷新
//        refreshLayout.autoRefresh();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        myVideoIndex = 1;
                        videoBeanList.clear();
                        myVideoAdapter.setNewData(videoBeanList);
                        loadMyData();
                        refreshLayout.finishRefresh();
                        refreshLayout.setNoMoreData(false);
                    }
                });
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        loadMyData();
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();
                    }
                });
            }
        });
        String id = getArguments().getString("userId");
        if (TextUtils.isEmpty(id)) {
            userId = TCUserMgr.getInstance().getUserId();
            loadMyUserInfo();
            guanzhuBtn.setVisibility(View.GONE);
        } else {
            guanzhuBtn.setVisibility(View.VISIBLE);
            userId = id;
            loadMyData();
            loadCollectData();
            loadVideoUserInfo();
        }
//        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setLayoutManager(new GridLayoutManager(recyclerView.getContext(), 2));
        myVideoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position > videoBeanList.size()) {
                    ToastUtils.showShort("数据错误");
                    return;
                }
                palyVideoList = MyAppUtils.getPlayVideoData(videoBeanList);
                startLivePlay(palyVideoList.get(position), position);
            }
        });

        likeRefreshLayout.setVisibility(View.GONE);
        likeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                likeRefreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        collectIndex = 1;
                        loadCollectData();
                        likeRefreshLayout.finishRefresh();
                        likeRefreshLayout.setNoMoreData(false);
                    }
                });
            }
        });

        likeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                likeRefreshLayout.getLayout().post(new Runnable() {
                    @Override
                    public void run() {
                        loadCollectData();
                        likeRefreshLayout.finishRefresh();
                        likeRefreshLayout.finishLoadMore();
                    }
                });
            }
        });

        likeRecyclerView.setLayoutManager(new GridLayoutManager(likeRecyclerView.getContext(), 2));
        likeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position > likeBeanList.size()) {
                    ToastUtils.showShort("数据错误");
                    return;
                }
                palyVideoList = MyAppUtils.getPlayVideoData(likeBeanList);
                startLivePlay(palyVideoList.get(position), position);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            loadMyData();
            loadCollectData();
        }
    }

    private void showUserInfoView(UserInfoBean collectBean) {
        if (collectBean == null)
            return;
        userNameTv.setText(MyAppUtils.getName(collectBean.getNickname()));
        Glide.with(mContext).load(collectBean.getAvatar()).error(R.drawable.face).into(userImageView);

    }

    private void loadVideoUserInfo() {
        RequestBody formBody = new FormBody.Builder()
                .add("userid", userId).build();
        HttpRequest.requestPost("personal_info", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data1) {
                JSONObject data = JSONObject.parseObject(data1);
                if (data == null)
                    return;
                JSONObject results = data.getJSONObject("results");
                if (results == null)
                    return;
                UserInfoBean collectBean = FastJsonTools.getPerson(results.toJSONString(), UserInfoBean.class);
                showUserInfoView(collectBean);
            }

            @Override
            public void onFailure(String data) {
            }
        });
    }

    private void loadMyUserInfo() {
        RequestBody formBody = new FormBody.Builder()
                .add("userid", userId + "").build();
        HttpRequest.requestPost("interest_list", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data1) {
                JSONObject data = JSONObject.parseObject(data1);
                if (data == null)
                    return;
                JSONObject results = data.getJSONObject("results");
                if (results == null)
                    return;
                collectBean = FastJsonTools.getPerson(results.toJSONString(), UserInfoBean.class);
                showUserInfoView(collectBean);
            }

            @Override
            public void onFailure(String data) {
            }
        });
    }

    int collectIndex = 1;

    /**
     * 获取收藏
     */
    private void loadCollectData() {
        RequestBody formBody = new FormBody.Builder()
                .add("userid", userId)
                .add("index", collectIndex + "")
                .add("count", Constant.SIZE + "").build();
        HttpRequest.requestPost("collection_list", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data) {
                CollectBean collectBean = FastJsonTools.getPerson(data, CollectBean.class);
                if (collectBean != null) {
                    // mVideoList.addAll();
                    int size = collectBean.getTotal();
                    if (collectIndex <= 1) {
                        likeBeanList.clear();
                        likeAdapter.setNewData(null);
                        likeAdapter.notifyDataSetChanged();
                    }
                    collectIndex++;
                    likeBeanList.addAll(collectBean.getList());
                    likeAdapter.setNewData(likeBeanList);
                    mineLikeVideo.setText("收藏" + collectBean.getTotal());
                    if (likeBeanList.size() >= size) {
                        likeAdapter.notifyDataSetChanged();
                        likeRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
            }

            @Override
            public void onFailure(String data) {
            }
        });
    }

    private int myVideoIndex = 1;

    private void loadMyData() {
        RequestBody formBody = new FormBody.Builder()
                .add("userid", userId)
                .add("index", myVideoIndex + "")
                .add("count", Constant.SIZE + "").build();

        HttpRequest.requestPost("get_work", formBody, new HttpResultListener() {
            @Override
            public void onSuccess(String data) {
                CollectBean collectBean = FastJsonTools.getPerson(data, CollectBean.class);
                if (collectBean != null) {
                    // mVideoList.addAll();
                    if (myVideoIndex <= 1) {
                        videoBeanList.clear();
                        myVideoAdapter.setNewData(null);
                    }
                    int size = collectBean.getTotal();
                    videoBeanList.addAll(collectBean.getList());
                    myVideoAdapter.setNewData(videoBeanList);
                    mineMyVideo.setText("我的视频" + collectBean.getTotal());
                    myVideoIndex++;
                    if (videoBeanList.size() >= size) {
                        myVideoAdapter.notifyDataSetChanged();
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
            }

            @Override
            public void onFailure(String data) {
            }
        });
    }


    /**
     * 开始播放视频
     *
     * @param item 视频数据
     */
    private void startLivePlay(final TCVideoInfo item, int position) {
        Intent intent = new Intent(getActivity(), TCVodPlayerActivity.class);
        intent.putExtra(TCConstants.PLAY_URL, item.playurl);
        intent.putExtra(TCConstants.PUSHER_ID, item.userid);
        intent.putExtra(TCConstants.PUSHER_NAME, item.nickname == null ? item.userid : item.nickname);
        intent.putExtra(TCConstants.PUSHER_AVATAR, item.headpic);
        intent.putExtra(TCConstants.COVER_PIC, item.frontcover);
        intent.putExtra(TCConstants.FILE_ID, item.fileid != null ? item.fileid : "");
        intent.putExtra(TCConstants.TCLIVE_INFO_LIST, (Serializable) palyVideoList);
        intent.putExtra(TCConstants.TIMESTAMP, item.createTime);
        intent.putExtra(TCConstants.TCLIVE_INFO_POSITION, position);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick({R.id.mine_my_video, R.id.mine_like_video, R.id.home_buy_btn, R.id.dianzhan_video_btn, R.id.guanzhu_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.guanzhu_btn:

                break;
            case R.id.home_buy_btn:
                WebViewActivity.actionStart(mContext, collectBean.getLink());
                break;
            case R.id.dianzhan_video_btn:
                CollectActivity.StartActivity(userId);
                break;

            case R.id.mine_my_video:
                refreshLayout.setVisibility(View.VISIBLE);
                likeRefreshLayout.setVisibility(View.GONE);
                myLikeLine.setVisibility(View.GONE);
                myVideoLine.setVisibility(View.VISIBLE);
                mineLikeVideo.setTextColor(ContextCompat.getColor(mContext, R.color.white));
                mineMyVideo.setTextColor(ContextCompat.getColor(mContext, R.color.black));

                break;
            case R.id.mine_like_video:
                refreshLayout.setVisibility(View.GONE);
                likeRefreshLayout.setVisibility(View.VISIBLE);
                myLikeLine.setVisibility(View.VISIBLE);
                myVideoLine.setVisibility(View.GONE);
                mineLikeVideo.setTextColor(ContextCompat.getColor(mContext, R.color.black));
                mineMyVideo.setTextColor(ContextCompat.getColor(mContext, R.color.white));
                break;
        }
    }

}
